package com.it.user.controller;

import com.github.pagehelper.PageInfo;
import com.it.base.utils.R;
import com.it.user.domain.User;
import com.it.user.query.UserQuery;
import com.it.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    @ApiOperation("查询所有用户")
    public R findAll() {
        List<User> userList = userService.findAll();
        return R.ok(userList);
    }

    @PostMapping
    @ApiOperation("分页查询用户")
    public PageInfo<User> queryPage(@RequestBody UserQuery userQuery) {
        PageInfo<User> pageInfo =userService.queryPage(userQuery);
        return pageInfo;
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public R delete(@PathVariable Long id) {
        try{
            userService.deleteUser(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除用户")
    public R batchUsers(@RequestBody Long[] ids) {
        try{
            userService.batchUsers(ids);
        }catch (Exception e){
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PutMapping
    @ApiOperation("添加用户OR更新用户")
    public R addUser(@RequestBody User user) {
        try{
            Long id = user.getId();
            if (id == null) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
